//
//  EmailLoginController.m
//  QRMaster
//
//  Created by myApple on 16/3/2.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "EmailLoginController.h"
#import "EmailLoginView.h"
#import "ForgetPWDViewController.h"
#import "QRTabbarController.h"
#import "MyRsa.h"
#import "RequestNetWork.h"
#import "userInfoModel.h"
#import "RegistLastViewController.h"
#import "RegistFirstStepViewController.h"
#import "Reachability.h"
#import "PromptInfoView.h"
#import "OpertionPlist.h"
#import "OperationDataBaseModel.h"
#import "OpertionPlist.h"
#import "GesturePasswordController.h"
#import "checkPower.h"
#import "MJExtension.h"
#import "CommunityListInfo.h"
#import "QRSingleton.h"
#import "faveriterCard.h"
#import "localizControllerViewController.h"
#import "MobileRegistFirstStepController.h"
#import "AreaChooseController.h"

@interface EmailLoginController ()<EmailLoginViewDelegate>
{
    NSMutableDictionary * dict;//存储个人信息的
    NSMutableArray * CommunityArray;
    NSUserDefaults * userInfo;
    EmailLoginView * emailView;
    QRSingleton * singleton;
    BOOL _isTrail;//是否试用
}

@end

@implementation EmailLoginController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dict = [[NSMutableDictionary alloc]init];
        CommunityArray = [[NSMutableArray alloc]init];
        singleton = [QRSingleton sharedQRSingleton];
        _isTrail = NO;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //    [self prepareTitleView];
    [self prepareView];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = NSLocalizedString(@"emailLogin", nil);
    userInfo = [NSUserDefaults standardUserDefaults];
    [userInfo setValue:nil forKey:@"token"];
    [userInfo setValue:nil forKey:@"login"];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    [data setValue:nil forKey:HOUSEINFO];
    [data setValue:nil forKey:STAFFINFO];
    [data setValue:nil forKey:COMMUNITYINFOFORKEY];
    [OpertionPlist writeDataToPlist:data];
    GesturePasswordController * gpc = [[GesturePasswordController alloc]init];
    [gpc clear];
    [userInfo setValue:@"0" forKey:@"gesture"];
}


-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - y;
    
    emailView = [[EmailLoginView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    emailView.delegate = self;
    [self.view addSubview:emailView];
    
}

-(void)getLoginData:(NSString *)uid PassWord:(NSString *)password
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSString * urlString = nil;
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:uid forKey:@"account"];
    [postDict setValue:[self getPassword:password] forKey:@"passwd"];
    urlString = POST(LOGIN);
    
    [rnk initWithPath:urlString params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            userInfoModel * model = [userInfoModel mj_objectWithKeyValues:[downLoadData objectForKey:@"data"]];
            model.uid = [[downLoadData objectForKey:@"data"] objectForKey:@"id"];
            if (![model.uid isEqualToString:[userInfo objectForKey:@"uid"]]) {
                //不是同一个人登录就去掉本地相关数据
                NSMutableDictionary * fileData = [OpertionPlist readDataFromPlist];
                [fileData setValue:nil forKey:FAVERITCARD];
                [OpertionPlist writeDataToPlist:downLoadData];
                //清除表信息
                OperationDataBaseModel * opData = [[OperationDataBaseModel alloc]init];
                [opData truncateTable];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"communityId"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                singleton.communityName = @"";
            }
            [userInfo setObject:model.uid forKey:@"uid"];
            [userInfo setObject:model.token forKey:@"token"];
            [userInfo setObject:@"logined" forKey:@"login"];//是否登录过来判断手势密码的显示问题
            [userInfo setValue:@"1" forKey:@"guestureCount"];//解决手势密码黑屏问题
            [userInfo setObject:model.email forKey:@"userMobile"];//记住登录号码
            [userInfo setObject:model.areaCode forKey:@"areaCode"];
            [userInfo synchronize];
             [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLaunch"];//不要启动介绍页面了
            [self getCommunityData];
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    }];
    
}

-(NSString *)getPassword:(NSString *)password
{
    MyRsa * rsa = [[MyRsa alloc]init];
    if (rsa != nil) {
        NSString * encryptPWD = [rsa RSAEncrypotoTheData:[NSString stringWithFormat:@"12345678%@",password] key:publicKeyString];
        encryptPWD = [encryptPWD stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return encryptPWD;
    }
    else
        return nil;
    
}


#pragma mark -- 获取集群信息
-(void)getCommunityData
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
        [self stopWaiting];
        if ([data objectForKey:@"data"] != nil) {
            CommunityListInfo * listInfo = [[CommunityListInfo alloc]init];
            NSDictionary * communityData = [data objectForKey:@"data"];
            CommunityArray = [communityData objectForKey:@"communities"];
            if (CommunityArray.count > 0) {
                for (int i=0; i<CommunityArray.count; i++) {
                    [listInfo deleteCommunityListInfo:[[CommunityArray objectAtIndex:i] objectForKey:@"communityid"]];
                    [listInfo insertCommunityListInfo:[[CommunityArray objectAtIndex:i] objectForKey:@"communityid"] withCommunityName:[[CommunityArray objectAtIndex:i] objectForKey:@"communityname"] withCommunityAreaCode:[[CommunityArray objectAtIndex:i] objectForKey:@"areaCode"]];
                    
                }
                if([[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"] == nil )
                {
                    singleton.communityId = [CommunityArray[0]objectForKey:@"communityid"];
                    singleton.communityName = [CommunityArray[0] objectForKey:@"communityname"];
                     singleton.currentAreaCodeString = [CommunityArray[0]objectForKey:@"areaCode"];
                    [[NSUserDefaults standardUserDefaults]setObject:singleton.communityId forKey:@"communityId"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
                else
                {
                    singleton.communityId = [[NSUserDefaults standardUserDefaults] objectForKey:@"communityId"];
                }
                
                [self getFaveriterCard];
            }
        }
        else if (error != nil) {
            if ([[error objectForKey:@"status"] integerValue] == 210) {//没有添加任何集群
                QRTabbarController * qrtc = [[QRTabbarController alloc]init];
                [self.navigationController pushViewController:qrtc animated:YES];
                qrtc.navigationController.navigationBarHidden = YES;
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
            
        }
    };
    
}

#pragma mark -- 获取网络收藏房卡信息
-(void)getFaveriterCard
{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(GETCOLLECTROOM) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            [faveriterCard writeFaveriterCard:[downLoadData objectForKey:@"data"]];
        }
        QRTabbarController * qrtc = [[QRTabbarController alloc]init];
        [self.navigationController pushViewController:qrtc animated:YES];
        qrtc.navigationController.navigationBarHidden = YES;
    }];
    
}

#pragma mark --- startpageviewdelegate
-(void)EmailLogin:(NSString *)uid PassWord:(NSString *)password
{
     [self getLoginData:uid PassWord:password];
}


-(void)emailForgetPassWord
{
    ForgetPWDViewController * fvwc = [[ForgetPWDViewController alloc]init];
    [self.navigationController pushViewController:fvwc animated:YES];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
